package com.firewolf.permission.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class ShiroUtil {

	/**
	 * 登录
	 * @param initFile : init文件 
	 * @param username : 账号
	 * @param password : 密码
	 */
	public static void login(String initFile, String username, String password) {
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:" + initFile);

		SecurityManager securityManager = factory.getInstance();

		SecurityUtils.setSecurityManager(securityManager);

		Subject subject = SecurityUtils.getSubject();

		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			System.out.println("登录失败");
		}
	}
	
	/**
	 * 获取主体信息
	 * @return
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
}
